'use strict';
const { Service } = require('egg');
class PageService extends Service {
  async page(params){
    const {ctx,app} = this;
    const condition = {}
    for(let key in params){
      if(params[key] && key!='v' && key!='page' &&  key!='each_page_num' && key!="model" && key!="order" && key!="asc"){
        condition[key] = params[key];
      }
    }
    params.page = params.page?params.page:1
    params.each_page_num = params.each_page_num?params.each_page_num:10
    params.page--
    params.each_page_num = parseInt(params.each_page_num);
    const orderBy =  [];
    const filds = ['createdAt',"DESC"];
    if(params.order){
      filds[0] = params.order;
    }
    if(params.asc){
      filds[1] = "asc"
    }
    orderBy.push(filds)
    const pages = await app.model[params.model].findAndCountAll(
      {attributes:{
        include: [
            [app.Sequelize.fn('date_format', app.Sequelize.col('createdAt'), '%Y-%m-%d %H:%i:%s'), 'createdAt'],
            [app.Sequelize.fn('date_format', app.Sequelize.col('updatedAt'), '%Y-%m-%d %H:%i:%s'), 'updatedAt'],
        ]
      },
        where:condition, offset: params.page*params.each_page_num, limit: params.each_page_num,order:orderBy
      }
    )
    const resutl = {code:1,data:pages.rows,sum_count:pages.count,page:++params.page,msg:""};
    return resutl;
  }
}

module.exports = PageService;
